import json

from django.contrib.auth import authenticate
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from libs.sinaweibopy3 import weiboApi
from oauth.models import OauthUser
from users.models import User
from rest_framework_jwt.serializers import jwt_payload_handler  # 根据用户,生成 jwt的payload部分内容
from rest_framework_jwt.serializers import jwt_encode_handler  # 根据payload内容, 生成token


class OauthWeibo(View):

    def post(self, request):
        # 返回 微博登录地址
        url = weiboApi.get_authorize_url()  # 生成了微博登录url
        return JsonResponse({'code': '0', 'msg': '成功', 'data': {'url': url}})


class OauthWeiboCallback(View):

    def post(self, request):
        # 根据code 从 微博服务器 换取 uid
        # 接收code ,
        code = request.GET.get('code')
        # 1. 根据code 换取 access_token,,weibo_uid
        data = weiboApi.request_access_token(code)
        if not data:
            # 没有取到token
            return JsonResponse({'code': 999, 'msg': 'token获取失败, 检查code是否过期'})
        access_token = data.access_token
        weibo_uid = data.uid
        print(weibo_uid)
        # 表,  美多id  微博id
        # 3. 根据uid 查询绑定情况
        try:
            weibo_user = OauthUser.objects.get(uid=weibo_uid)
        except Exception as e:
            # weibo_user = None
            return JsonResponse({'code': '0',
                                 'msg': '需要绑定用户',
                                 'type': '0',  # type : 0: 需要绑定,  美多账号, 美多密码  => 美多用户
                                 'weibo_uid': weibo_uid})  # 可以拿到 微博uid
        user = weibo_user.user  # 这个就是美多用户
        payload = jwt_payload_handler(user)  # 根据用户,生成 jwt的payload部分内容
        token = jwt_encode_handler(payload)  # 根据payload内容, 生成token
        return JsonResponse({'username': user.username,
                             'id': user.id,
                             'token': token})

        # try:
        #     oauth_user = OauthUser.objects.get(uid=weibo_uid, oauth_type='1')
        # except Exception as e:
        #     oauth_user = None
        # # 返回动作,  登录成功/需要绑定用户 type 0 登录成功,  1, 授权成功, 需要绑定
        # if oauth_user:
        #     # 4. 如果绑定了, 返回token, 登录成功
        #     user = oauth_user.user
        #     return JsonResponse({'code': '0', 'msg': '登录成功',
        #                          'username': user.username,
        #                          'id': user.id,
        #                          'token': '000'})
        # else:
        #     # 5. 如果没绑定, 返回标志, 让前端跳转到绑定页面
        #     return JsonResponse({'code': 0, 'msg': '授权成功', 'data': {'type': '1', 'uid': weibo_uid}})
        #


class OauthWeiboBindUser(View):

    def post(self, request):
        # 绑定用户, 1. 已注册用户, 2. 未注册用户
        # 1.1 获取用户名, 密码, weibo_uid
        """
          password: this.password,
          mobile: this.mobile,
          sms_code: this.sms_code,
          weibo_uid: this.weibo_uid
        """
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        weibo_uid = data.get('weibo_uid')
        if not all([mobile, password, sms_code, weibo_uid]):
            return JsonResponse({'code': 999, 'msg': '参数不全'})
        # 0.判断是否存在此用户
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            user = None
        # 1. 已注册用户
        if user:
            # 1.2 , 如果存在就验证 密码, 验证通过,就绑定, 返回token,登录成功
            if user.check_password(password):
                ou = OauthUser(uid=weibo_uid, user=user)
                ou.save()
                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)
                return JsonResponse({'username': user.username,
                                     'id': user.id,
                                     'token': token})
            else:
                return JsonResponse({'code': '999', 'msg': '用户已存在, 但是密码错误, 绑定失败'})
        else:
            # 2. 未注册用户
            # 2.1 生成新用户, 设置用户名密码, 保存, 然后绑定, 返回token, 登录成功
            user = User(username='md%s' % mobile, mobile=mobile)  # md13312341234
            user.set_password(password)
            user.save()
            ou = OauthUser(uid=weibo_uid, user=user)
            ou.save()
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return JsonResponse({'username': user.username,
                                 'id': user.id,
                                 'token': token})